package praktikumid.w03.p5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Example program which asks user input in the form &lt;name&gt;, &lt;age&gt;.
 * Name and age is stored in Person object and all the entries are stored in
 * ArrayList. When user enters "exit" program writes out all the Person
 * objects stored in the list.
 * @author Ago
 *
 */
public class NameAge {

	
	/**
	 * Main method.
	 * @param args Command line arguments.
	 * @throws IOException If an input or output exception occurs.
	 */
	public static void main(String[] args) throws IOException {
		
		// let's use ArrayList, which can dynamically expand
		// <Person> indicates the data type of every element in the list
		ArrayList<Person> persons = new ArrayList<Person>();
		// Person[] persons = new Persons[100];
		BufferedReader br = new BufferedReader(
				new InputStreamReader(System.in));
		while (true) {
			System.out.println("enter <name>, <age> (\"exit\" to quit):");
			String line = br.readLine();
			if (line.equals("exit")) {
				break;
			}
			String[] tokens = line.split(","); // mati, 12
			// one comma expects 2 tokens ("mati" and " 12")
			if (tokens.length != 2) {
				// if there are more or less tokens than 2, 
				// then there are probably
				// more or less commas
				System.out.println("Format should be <name>, <age> (exactly 1 comma)!");
				// let's use continue to actually
				// go back to the beginning of while loop
				continue;
			}
			Person p = new Person();
			
			p.name = tokens[0].trim();
			try {
				// first, trim the second token (age)
				// and then try to parse it as integer
				p.age = Integer.parseInt(tokens[1].trim());
				// if we have reached here, no error occurred
				// therefore we can add the person p to the list
				persons.add(p);
			} catch (NumberFormatException e) {
				System.out.println("not a number");
			}
			
		}
		
		for (Person p : persons) {
			System.out.println(p);
		}
		/*for (int i = 0; i < persons.size(); i++) {
			System.out.println(persons.get(i));
		}*/
	}

}
